/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jfrmNovoUsuario.java
 *
 * Created on 05/11/2011, 13:44:41
 */
package br.ufc.si.poo.orkut.gui;

import br.ufc.si.poo.orkut.beans.comunidade.Comunidade;
import br.ufc.si.poo.orkut.beans.forum.Forum;
import br.ufc.si.poo.orkut.beans.usuario.Usuario;
import br.ufc.si.poo.orkut.beans.usuario.UsuarioComum;
import br.ufc.si.poo.orkut.beans.usuario.UsuarioVip;
import java.util.Map;
import javax.swing.JOptionPane;

/**
 *
 * @author italoney
 */
public class jfrmNovoUsuario extends javax.swing.JFrame {

    //<editor-fold defaultstate="collapsed" desc="Membros privados">
    private Map<String, Comunidade> comunidades;
    private Map<String, Usuario> usuarios;
    private Map<String, Forum> foruns;
    //</editor-fold>   

    /** Creates new form jfrmNovoUsuario */
    public jfrmNovoUsuario() {
        initComponents();
    }

    /**
     * @author italoney
     * Contrutor para inicializar propriedades
     * @param comunidades comunidades disponiveis
     * @param usuarios usuários disponiveis
     * @param foruns foruns disponiveis
     */
    public jfrmNovoUsuario(Map<String, Comunidade> comunidades, Map<String, Usuario> usuarios, Map<String, Forum> foruns) {
        initComponents();

        this.comunidades = comunidades;
        this.usuarios = usuarios;
        this.foruns = foruns;
        inicializarCampos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        setUndecorated(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Digite os dados do usuario", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jTextField2.setText("jtxtIdadeUsuario");
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField2KeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField2KeyPressed(evt);
            }
        });

        jTextField1.setText("jtxtNomeDoUsuario");

        jLabel2.setText("Idade:");

        jCheckBox1.setText("VIP");

        jLabel1.setText("Nome:");

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jCheckBox1))
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(jButton1)
                        .addGap(27, 27, 27)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-370)/2, (screenSize.height-174)/2, 370, 174);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jTextField1.getText() != null && !jTextField1.getText().equals("")) {
            if (jTextField2.getText() != null && !jTextField2.getText().equals("")) {
                if (!this.usuarios.containsKey(jTextField1.getText())) {
                    if (jCheckBox1.isSelected()) {
                        UsuarioVip uv = new UsuarioVip();
                        uv.setNome(jTextField1.getText());
                        int idade = 0;
                        try {
                            idade = Integer.parseInt(jTextField2.getText());

                            while (!validaIdade(idade)) {
                                JOptionPane.showMessageDialog(null, "Idade deve ser maior ou igual a 18!", "Erro", JOptionPane.ERROR_MESSAGE);
                                jTextField2.setText("");
                                return;
                            }

                            uv.setIdade(idade);

                            this.usuarios.put(uv.getNome(), uv);
                            jfrmPrincipal manager = new jfrmPrincipal();
                            manager.adicionarUsuario(this.usuarios);
                            this.dispose();
                        } catch (NumberFormatException ex) {
                            JOptionPane.showMessageDialog(null, "Idade deve conter apenas numeros!", "Erro", JOptionPane.ERROR_MESSAGE);
                        }

                    } else {
                        UsuarioComum uc = new UsuarioComum();
                        uc.setNome(jTextField1.getText());
                        int idade = 0;
                        try {
                            idade = Integer.parseInt(jTextField2.getText());
                            while (!validaIdade(idade)) {
                                JOptionPane.showMessageDialog(null, "Idade deve ser maior ou igual a 18!", "Erro", JOptionPane.ERROR_MESSAGE);
                                jTextField2.setText("");
                                return;
                            }
                            uc.setIdade(idade);
                            this.usuarios.put(uc.getNome(), uc);

                            jfrmPrincipal manager = new jfrmPrincipal();
                            manager.atualizarListas(this.comunidades, this.usuarios, this.foruns);
                            this.dispose();
                        } catch (NumberFormatException ex) {
                            JOptionPane.showMessageDialog(null, "Idade deve conter apenas numeros!", "Erro", JOptionPane.ERROR_MESSAGE);
                        }

                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Este nome usuário já existe, digite outro nome", "Erro",
                            JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Digite a idade do usuário", "Erro",
                        JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Digite o nome do usuario", "Erro",
                    JOptionPane.ERROR_MESSAGE);
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jfrmPrincipal manager = new jfrmPrincipal();
        manager.atualizarListas(this.comunidades, this.usuarios, this.foruns);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyTyped
    }//GEN-LAST:event_jTextField2KeyTyped

    private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyPressed
    }//GEN-LAST:event_jTextField2KeyPressed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new jfrmNovoUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables

    /**
     * @author italoney
     * Inicializar os campos do formulário
     */
    private void inicializarCampos() {

        jTextField1.setText("");
        jTextField2.setText("");
    }

    /**
     * @author italoney
     * Validar a idade do uauário
     * @param idade idade do usuário
     * @return true ou false
     */
    private boolean validaIdade(int idade) {
        if (idade >= 18) {
            return true;
        }

        return false;
    }
}
